package com.albermark.photoorganizer.scanner;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.ParseException;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

import com.albermark.photoorganizer.pojo.Photo;
import com.drew.imaging.ImageProcessingException;

/**
 * 
 * @author Nuno Ferreira
 *
 */
public class PhotoFileScanner extends Thread {
	
	private static Logger LOG = Logger.getLogger(PhotoFileScanner.class);

	private int foldersScanned = 0;
	private int photosFound = 0;
	
	private final File rootFolder;
	private final FileFilter fileFilter;
	private BlockingQueue<Photo> foundPhotosQueue;

	
	public PhotoFileScanner(String processName, File rootFolder, FileFilter fileFilter, BlockingQueue<Photo> foundPhotosQueue) {
		
		Assert.notNull(fileFilter);

		setName(processName);
		this.rootFolder = rootFolder;
		this.fileFilter = fileFilter;
		this.foundPhotosQueue = foundPhotosQueue;
	}
	
	@Override
	public void run() {
		try {
			scan(rootFolder);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		LOG.info("Scan finished for root folder: " + rootFolder.getAbsolutePath());
	}
	
	
	/**
	 * 
	 * @param folder
	 * @throws InterruptedException
	 * @throws ImageProcessingException
	 * @throws ParseException
	 * @throws IOException
	 */
	public void scan(File folder) throws InterruptedException, ImageProcessingException, ParseException, IOException {

		foldersScanned++;
		if (foldersScanned % 10 == 0) {
			LOG.info(foldersScanned + " folders scannned so far. Queue size: " + foundPhotosQueue.size() + ". Currently scanning: " + folder.getAbsolutePath());
		}
		
		Assert.notNull(folder);
		
		File[] filesFound = folder.listFiles(fileFilter);
		
		if (filesFound == null || filesFound.length == 0) {
			
			LOG.info("No JPG files found at: " + folder.getAbsolutePath());
			return;
		}
		
		
		for (File fileFound : filesFound) {
			try {
				
				if (fileFound.getName().startsWith(".")) continue;

				if (fileFound.isDirectory()) {
					
					scan(fileFound);
					
				} else {
					
					Photo photo = new Photo(fileFound);	
					foundPhotosQueue.put(photo);
					
					photosFound++;
					if (photosFound % 10 == 0) {
						LOG.info("Photos found: " + photosFound);
					}
				}
			
			} catch (Exception e) {
				LOG.error("Error opening file: " + fileFound.getAbsolutePath());

				e.printStackTrace();
			}
		}
	}
}
